package com.audaque.springboot.foshanupload.redis.component;

import com.audaque.springboot.foshanupload.core.exception.RetryMaxException;

import com.audaque.springboot.foshanupload.core.exception.RetryingException;
import com.audaque.springboot.foshanupload.redis.model.dto.AsyncResultDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;

/**
 * @author zgb
 * @desc ...
 * @date 2022-02-28 20:17:55
 */
@Slf4j
@Component
public class AsyncWaiter {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AsyncRetryer asyncRetryer;



    public AsyncResultDto waitFinish(String paramCountKey, String productCountKey, String consumeCountKey,String reportListSizeKey,String overListSizeKey) {
        log.debug("s:waitFinish");

        //等待上报办结结束
        this.retryUntilSuccess(paramCountKey,  productCountKey,  consumeCountKey, reportListSizeKey, overListSizeKey);

        //获取上报办结结果
        AsyncResultDto asyncResultDto = new AsyncResultDto();
        asyncResultDto.setParamInteger(Integer.parseInt(stringRedisTemplate.opsForValue().get(paramCountKey)));
        asyncResultDto.setProductInteger(Integer.parseInt(stringRedisTemplate.opsForValue().get(productCountKey)));
        asyncResultDto.setConsumeInteger(Integer.parseInt(stringRedisTemplate.opsForValue().get(consumeCountKey)));
        log.debug("上报：listForeachEventAsyncResultDto：" + asyncResultDto);

        log.debug("e:waitFinish");
        return asyncResultDto;
    }

    private  void retryUntilSuccess(String paramCountKey, String productCountKey, String consumeCountKey,String reportListSizeKey,String overListSizeKey){
        try {
            asyncRetryer.retry( paramCountKey,  productCountKey,  consumeCountKey, reportListSizeKey, overListSizeKey);
        } catch (RetryMaxException e) {
            log.debug("等待上报办结结束,重试次数达到上限，继续重试");
            retryUntilSuccess( paramCountKey,  productCountKey,  consumeCountKey,  reportListSizeKey, overListSizeKey);
        }
    }


}
